using System.Collections.Specialized;

namespace Infrastructure
{
    /// <summary>
    /// 获取访问Web服务器的客户端IP的辅助类
    /// </summary>
    public static class IPHelper
    {
        /// <summary>
        /// 获取代理IP(HTTP_X_FORWARDED_FOR服务器变量)
        /// </summary>
        /// <param name="serverVariables">服务器变量集合</param>
        /// <returns>代理IP，无则返回空字符串</returns>
        public static string GetProxyIP(NameValueCollection serverVariables)
        {
            // 返回代理IP
            return serverVariables.Get("HTTP_X_FORWARDED_FOR");
        }

        /// <summary>
        /// 获取远程IP(Remote_Addr服务器变量)
        /// </summary>
        /// <param name="serverVariables">服务器变量集合</param>
        /// <returns>远程IP，无则返回空字符串</returns>
        public static string GetRemoteIP(NameValueCollection serverVariables)
        {
            // 返回远程IP
            return serverVariables.Get("Remote_Addr");
        }

        /// <summary>
        /// 获取完整的IP(HTTP_X_FORWARDED_FOR及Remote_Addr服务器变量)
        /// </summary>
        /// <param name="serverVariables">服务器变量集合</param>
        /// <returns>完整的IP，格式为远程IP(代理IP，无代理IP不包含括号)。无则返回空字符串</returns>
        public static string GetIP(NameValueCollection serverVariables)
        {
            // 得到代理IP和远程IP
            string proxyIP = serverVariables.Get("HTTP_X_FORWARDED_FOR");
            string romoteIP = serverVariables.Get("Remote_Addr");
            string ip = string.Empty;

            // 合成IP
            if (!string.IsNullOrEmpty(romoteIP))
                ip = romoteIP.Trim();

            if (!string.IsNullOrEmpty(proxyIP))
                ip += string.Format("({0})", proxyIP.Trim());

            return ip;
        }

    }
}
